#!/bin/bash

# 调试面板服务器管理脚本

PORT=3000

check_port() {
    local pid=$(lsof -ti:$PORT 2>/dev/null | head -n1)
    if [ ! -z "$pid" ]; then
        echo "端口 $PORT 被进程 $pid 占用"
        return 0
    else
        echo "端口 $PORT 空闲"
        return 1
    fi
}

start_server() {
    echo "🚀 启动调试面板服务器..."
    
    # 检查端口是否被占用
    if check_port; then
        echo "❌ 端口已被占用，请先停止服务器"
        return 1
    fi
    
    # 启动服务器
    npm run server &
    
    # 等待服务器启动
    sleep 3
    
    if check_port; then
        echo "✅ 服务器启动成功！"
        echo "📍 HTTP Server: http://10.240.20.130:$PORT"
        echo "🔌 WebSocket Server: ws://10.240.20.130:$PORT"
        echo "🎮 Debug Panel: http://10.240.20.130:$PORT/debug-panel.html"
        return 0
    else
        echo "❌ 服务器启动失败"
        return 1
    fi
}

stop_server() {
    echo "🛑 停止调试面板服务器..."
    
    local pids=$(lsof -ti:$PORT 2>/dev/null)
    if [ ! -z "$pids" ]; then
        echo "$pids" | xargs kill -9
        echo "✅ 服务器已停止 (PIDs: $pids)"
    else
        echo "ℹ️ 服务器未运行"
    fi
}

restart_server() {
    echo "🔄 重启调试面板服务器..."
    stop_server
    sleep 2
    start_server
}

status_server() {
    echo "📊 服务器状态："
    if check_port; then
        echo "✅ 服务器正在运行"
        echo "🌐 访问地址："
        echo "  - HTTP: http://10.240.20.130:$PORT"
        echo "  - WebSocket: ws://10.240.20.130:$PORT"
        echo "  - Debug Panel: http://10.240.20.130:$PORT/debug-panel.html"
    else
        echo "❌ 服务器未运行"
    fi
}

case "$1" in
    start)
        start_server
        ;;
    stop)
        stop_server
        ;;
    restart)
        restart_server
        ;;
    status)
        status_server
        ;;
    *)
        echo "调试面板服务器管理工具"
        echo ""
        echo "使用方法: $0 {start|stop|restart|status}"
        echo ""
        echo "  start   - 启动服务器"
        echo "  stop    - 停止服务器"
        echo "  restart - 重启服务器"
        echo "  status  - 查看服务器状态"
        echo ""
        exit 1
        ;;
esac

exit $?
